/**
 * Created by lmn98 on 2017/5/24.
 */
//时间转秒
var timeToSec = function(str) {
    var times = str.split(':');
    if(times.length !== 3) return null;
    return times[0]*3600 + times[1]*60 + times[2]*1;
};

var ffmpeg = require('fluent-ffmpeg');
var workQueue = [];
var command= null;
var reduce = function (work) {
    working = work.workNo;
    ffmpeg.ffprobe(work.filePath, function (e, data) {
        if(e) {
            working = null;
            getToWork();
            return;
        }
        var duration = data.streams[0].duration;
        if(isNaN(durantion) && data.streams[0].hasOwnProperty('tags')) {
            durantion = timeToSec(data.streams[0].tags.DURATION);
        } else {
            duration = 99999;
        }
        var start = work.start || 0;
        var end = work.end && work.end<duration ? work.end: duration;
        command = ffmpeg(work.filePath).videoCodec('libx264');  //编码
        if(work.size) {
            command.size(work.size+'x?');
        }
        if(work.aspect) {
            command.aspect(work.aspect);
        }
        if(work.start) {
            command.seek(start);
        }
        if(work.end) {
            command.duration(end-start);
        }
        command.on('start', function () {
            console.log('Work '+work.workNo+' start.')
        }).on('error', function(err) {
            process.send({
                workNo: work.workNo,
                errormsg: err.message
            });
            console.log(err.message);
            working = null;
            getToWork();
        }).on('end', function() {
            process.send({
                workNo: work.workNo
            });
            console.log('Work '+work.workNo+' end.');
            working = null;
            getToWork();
        })
        .toFormat('mp4')
        .saveToFile(work.savePath);
    });

};
var screenShort = function (work) {
    working = work.workNo;
    command = ffmpeg(work.filePath)
        .on('start', function () {
            console.log('Work '+work.workNo+' start.')
        })
        .on('end', function() {
            process.send({
                workNo: work.workNo
            });
            console.log('Work '+work.workNo+' end.');
            working = null;
            getToWork();
        })
        .screenshots({
            // Will take screens at 20%, 40%, 60% and 80% of the video
            count: 9,
            filename: 'thumbnail_'+work.name+'%i.png',
            folder: work.savePath,
            size: '480x270'
        });
};
var working = null;
var getToWork = function () {
    if(working) return;
    var work = workQueue.shift();
    if(work){
        switch (work.command){
            case 1: {
                reduce(work);
                break;
            }
            case 2: {
                screenShort(work);
                break;
            }
        }
    }
};
var stopWork = function (workNo) {
    if(working === workNo && command){
        command.kill();
        working = null;
        getToWork();
    }else{
        for(var i=0,l=workQueue.length;i<l;i++){
            if(workQueue[i].workNo === workNo){
                workQueue.splice(i,1);
                break;
            }
        }
    }
};
process.on('message', function (msg) {
    if(msg.command === -1){
        stopWork(msg.workNo)
    }else{
        workQueue.push(msg);
        getToWork();
    }
});
